#include "contacts.pb.h"
#include <iostream>
#include <fstream>

int main()
{
    // 将通讯录文件中的所有信息读取出来
    std::ifstream ifs("contacts.bin", std::ios::in | std::ios::binary);
    contacts2::Contacts contacts;

    if (!ifs)
    {
        std::cerr << "打开通讯录失败" << std::endl;
        ifs.close();
        return -1;
    }

    if (!contacts.ParseFromIstream(&ifs))
    {
        std::cerr << "读取通讯录失败" << std::endl;
        ifs.close();
        return -2;
    }

    if (contacts.info_size() == 0)
    {
        std::cout << "通讯录为空..." << std::endl;
        ifs.close();
        return 0;
    }

    // 打印到控制台
    for (int i = 0; i < contacts.info_size(); i++)
    {
        std::cout << "----------联系人" << i + 1 << "--------" << std::endl;
        auto info = contacts.info(i);
        std::cout << "姓名: " << info.name() << std::endl;
        std::cout << "年龄: " << info.age() << std::endl;

        for (int j = 0; j < info.phone_size(); j++)
        {
            contacts2::PeopleInfo_Phone phone = info.phone(j);
            if (phone.type() == contacts2::PeopleInfo_Phone_PhoneType::PeopleInfo_Phone_PhoneType_MOB)
                std::cout << "电话" << j << ": " << phone.number() << " (移动电话)" << std::endl;
            else
                std::cout << "电话" << j << ": " << phone.number() << " (固定电话)" << std::endl;
        }

        if (info.has_data() && info.data().Is<contacts2::Address>()) // 判断any数据类型是否为 "地址"
        {
            contacts2::Address addr;
            info.data().UnpackTo(&addr);

            std::cout << "家庭地址: " << addr.home_addr() << std::endl;
            std::cout << "单位地址: " << addr.unit_addr() << std::endl;
        }

        switch (info.other_contact_case())
        {
        case contacts2::PeopleInfo::OtherContactCase::kQq:
            std::cout << "QQ: " << info.qq() << std::endl;
            break;
        case contacts2::PeopleInfo::OtherContactCase::kWechat:
            std::cout << "微信: " << info.wechat() << std::endl;
            break;
        default:
            break;
        }

        std::cout << "备注: " << std::endl;
        for(auto kv : info.comments())
        {
            std::cout << "\t";
            std::cout << kv.first << ": " << kv.second << std::endl;
        }

        std::cout << "--------------------------" << std::endl;
    }
    ifs.close();

    return 0;
}